package com.reducejoin;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapreduce.Mapper;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class TableMapper extends Mapper<LongWritable, Text, Text, TableBean> {

    private String filename;
    private Text outK = new Text();
    private TableBean outV = new TableBean();
    private Map<String, String> pdMap = new HashMap<>();

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] line = value.toString().split("\t");

//        if (filename.equals("order")){
//            outK.set(line[1]);
//            outV.setId(line[0]);
//            outV.setPid(line[1]);
//            outV.setAmount(Integer.parseInt(line[2]));
//            outV.setPname("");
//            outV.setFlag("order");
//        } else {
//            outK.set(line[0]);
//            outV.setPname(line[1]);
//            outV.setPid(line[0]);
//            outV.setAmount(0);
//            outV.setId("");
//            outV.setFlag("pd");
//        }

        String pname = pdMap.get(line[1]);
        outK.set(line[1]);
        outV.setId(line[0]);
        outV.setPid(line[1]);
        outV.setAmount(Integer.parseInt(line[2]));
        outV.setPname(pname);
        context.write(outK, outV);
    }

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
//        // 获取对应文件名称
//        FileSplit split = (FileSplit) context.getInputSplit();
//        filename = split.getPath().getName();

        URI[] cacheFiles = context.getCacheFiles();
        Path path = new Path(cacheFiles[0]);

        FileSystem fs = FileSystem.get(context.getConfiguration());
        FSDataInputStream fis = fs.open(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

        String line;
        while (StringUtils.hasText(line = reader.readLine())) {
            String[] split = line.split("\t");
            pdMap.put(split[0], split[1]);
        }

        IOUtils.closeStream(reader);


    }


}
